<template>
  <div class="lendWrap">
    <div class="lend-bg"></div>
    <div class="lend-box">
      <div class="lend-limit" :class="{'num':showStart==false}">
        <span class="limit-word">借支额度：</span>
        <span v-text="limit" :class="{'limit_num':showStart==true}"></span>
      </div>

      <div class="lend-company">
        <span class="name">公司名称：</span>
        <div class="company" v-text="company" @click="openCompanyList"></div>
        <img src="./pull.png" class="pull" onclick="return false"/>
      </div>

      <div class="lend-con">
        <span class="title">驻厂手机：</span>
        <div class="phone-box">
          <input type="text" class="phone" maxlength="11" v-model="phone" placeholder="请输入驻厂手机号" @blur="inputBlur"/>
        </div>
      </div>
      <div class="lend-con">
        <span class="title">借支金额：</span>
        <div class="phone-box">
          <input type="text" class="phone" v-model="lendMoney" placeholder="请输入借支金额" @blur="inputBlur"/>
        </div>
      </div>

      <div class="lend-photo">
        <div class="name">上传图片：</div>
        <div class="photo-box">
          <div class="camera-box">
            <img src="./camera.png" class="camera" onclick="return false"/>
            <span class="upload">点击上传</span>
            <input type="file" accept="image/*" class="photo" @change="uploadPhoto($event)"/>
          </div>
          <div class="tips">用户申请借支时，上传工资表或者考勤记录，驻厂会优先审核。</div>
        </div>
        <img :src="camera" class="uploadImg" v-if="upload" onclick="return false"/>
      </div>

      <div class="lend-word">
        温馨提示：每周借支额度的上限由入职的企业决定，借支的金额将在每月发工资时进行扣取。
      </div>

      <div class="lend-btn">
        <button type="button" class="sure" @click="lend">确定</button>
      </div>

      <!--借支公司列表-->
      <div class="company-box" v-show="showCompany" @click="closeCompanyList">
        <div class="company-list">
          <div class="name" v-for="(item,index) in companyList" :key="index"
               @click="selectCompany(item.id,item.mechanismName)">{{item.mechanismName}}
          </div>
        </div>
      </div>
    </div>

    <!--微信绑定手机号-->
    <v-phone v-model="showModal" @bindPhone="bindCustomerPhone"></v-phone>

    <v-warn content="您尚未添加银行卡，暂不支持借支，是否前往添加？" confirmText="是" v-model="sendVal" @confirm="confirm"></v-warn>

    <v-dialog v-model="modalVal" :content="content" cancelText="取消" confirmText="去绑定" @confirm="bindPage"
              @cancel="cancel"></v-dialog>

  </div>
</template>

<script>
  import phone from "../../components/phone"
  import {Base64} from 'js-base64'
  import {baseUrl} from "../../config/env"
  import * as util from "../../config/util"
  import warn from "../../components/warn"
  import * as qiniu from 'qiniu-js'
  import dialog from "../../components/dialog"

  export default {
    data() {
      return {
        phone: "",
        company: "请选择企业",
        limit: "***",
        lendMoney: "",
        camera: "",
        userSign: "",
        upload: false,
        showModal: false,
        openid: "",
        userName: "",
        userUrl: "",
        countentPhone: "",
        companyList: [],
        showCompany: false,
        showStart: true,
        sendVal: false,
        mechanismId: "",
        photo: "",
        modalVal: false,
        content: "您还未绑定工资卡，请先绑定再借支"
      }
    },
    mounted() {
      this.openid = util.getUrlKey("openid"); //微信openid
      this.userName = util.getUrlKey("userName"); //用户昵称
      this.userUrl = util.getUrlKey("userUrl"); //用户头像
      this.countentPhone = util.getUrlKey("countentPhone"); //手机框 0弹出1不弹出

      if (this.openid != "" && this.openid != "null" && this.openid != null) {
        util.setSessionStore("openid", Base64.encode(this.openid));
      }
      if (this.userName != "" && this.userName != "null" && this.userName != null) {
        this.userName = decodeURI(this.userName);
        util.setSessionStore("weixin_userName", this.userName);
      }
      if (this.userUrl != "" && this.userUrl != "null" && this.userUrl != null) {
        util.setSessionStore("weixin_userUrl", this.userUrl);
      }

      this.userSign = Base64.decode(util.getSessionStore("openid"));
      if (this.countentPhone == "0") {
        this.showModal = true;
      } else {
        this.axios.get(baseUrl + "/billrecord/query_bankcardwithDraw?sgin=" + this.userSign).then((res) => {
          let resultObj = res.data;
          if (resultObj.code == 0 && resultObj.data != null) {
            if (resultObj.data.type == 1) { //没有绑定银行卡
              this.modalVal = true;
            } else {
              if (util.getSessionStore("lend_type") != "1") {
                //查询是否有借支记录
                this.axios.get(baseUrl + "/lendmoney/query_checkrecord?sgin=" + this.userSign).then((res) => {
                  let resultObj = res.data;
                  if (resultObj.code == 0 && resultObj.data != null) {
                    this.$router.push("/lendDetail");
                  }
                })
              }

              //查询借支公司列表
              this.axios.get(baseUrl + "/lendmoney/query_mechanism?sgin=" + this.userSign).then((res) => {
                let resultObj = res.data;
                if (resultObj.code == 0 && resultObj.data.length > 0) {
                  this.companyList = resultObj.data;
                } else {
                  this.$vux.toast.text(resultObj.msg, "middle");
                }
              })
            }
          } else {
            this.$vux.toast.text(resultObj.msg, "middle");
          }
        }).catch(() => {
          this.$vux.toast.text("网络异常", "middle");
        });
      }
    },
    methods: {
      cancel() {
        this.modalVal = false;
      },
      bindPage() {
        this.modalVal = false;
        sessionStorage.setItem("lend_sign", "001199");
        this.$router.push("/paycardManage");
      },
      checkMoney() {//校验金额
        let reg = /^[0-9]*[1-9][0-9]*$/;
        if (this.lendMoney == "" || this.lendMoney == null) {
          this.$vux.toast.text("请输入借支金额", "middle");
          return;
        } else if (!reg.test(this.lendMoney)) {
          this.$vux.toast.text("请输入正确的整数金额", "middle");
          return;
        } else if (eval(this.lendMoney) > eval(this.limit)) {
          this.$vux.toast.text("借支金额超过可借支额度", "middle");
          return;
        } else if (eval(this.limit) == 0) {
          this.$vux.toast.text("暂时不可借支", "middle");
          return;
        }
        return true;
      },
      checkCompany() {//校验企业
        let value = this.company == "请选择企业" ? "" : this.company;
        if (value == "" || value == undefined) {
          this.$vux.toast.text("请选择公司", "middle");
          return;
        }
        return true;
      },
      checkPhone() {//校验驻厂手机
        let reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
        if (this.phone == "") {
          this.$vux.toast.text("手机号码不能为空", "middle");
          return;
        } else if (!reg.test(this.phone)) {
          this.$vux.toast.text("手机号码格式错误", "middle");
          return;
        }
        return true;
      },
      bindCustomerPhone(phone) { //绑定微信手机
        this.$vux.loading.show({
          text: '加载中',
        })
        this.axios.get(baseUrl + "/wx_user/set_phone?sgin=" + this.userSign + "&phone=" + phone + "&userName=" + this.userName + "&userUrl=" + this.userUrl).then((res) => {
          let resultObj = res.data;
          this.$vux.loading.hide();
          if (resultObj.code == 0 && resultObj.data == 1) {
            this.axios.get(baseUrl + "/billrecord/query_bankcardwithDraw?sgin=" + this.userSign).then((res) => {
              let resultObj = res.data;
              if (resultObj.code == 0 && resultObj.data != null) {
                if (resultObj.data.type == 1) { //没有绑定银行卡
                  this.modalVal = true;
                } else {
                  if (util.getSessionStore("lend_type") != "1") {
                    //查询是否有借支记录
                    this.axios.get(baseUrl + "/lendmoney/query_checkrecord?sgin=" + this.userSign).then((res) => {
                      let resultObj = res.data;
                      if (resultObj.code == 0 && resultObj.data != null) {
                        this.$router.push("/lendDetail");
                      }
                    })
                  }

                  //查询借支公司列表
                  this.axios.get(baseUrl + "/lendmoney/query_mechanism?sgin=" + this.userSign).then((res) => {
                    let resultObj = res.data;
                    if (resultObj.code == 0 && resultObj.data.length > 0) {
                      this.companyList = resultObj.data;
                    } else {
                      this.$vux.toast.text(resultObj.msg, "middle");
                    }
                  })
                }
              } else {
                this.$vux.toast.text(resultObj.msg, "middle");
              }
            }).catch(() => {
              this.$vux.toast.text("网络异常", "middle");
            });
          } else {
            this.showModal = true;
            this.$vux.toast.text(resultObj.msg, "middle");
          }
        }).catch((error) => {
          this.$vux.loading.hide();
          this.$vux.toast.text("网络异常", "middle");
        });
      },
      selectCompany(id, name) {//选择借支公司
        this.showCompany = false;
        this.company = name;
        this.mechanismId = id;
        //查询是否允许借支
        this.axios.get(baseUrl + "/lendmoney/query_isLend_api?sgin=" + this.userSign + "&mechanismId=" + id).then((res) => {
          let resultObj = res.data;
          if (resultObj.data.res_code == 0) {
            this.showStart = false;
            this.limit = util.toDecimal(resultObj.data.lendMoney);
          } else if (resultObj.data.res_code == 20010) {//未添加银行卡，暂不支持借支
            // this.sendVal = true;
          } else {
            this.$vux.toast.text(resultObj.msg, "middle");
          }
        }).catch((error) => {
          this.$vux.toast.text("网络异常", "middle");
        });
      },
      openCompanyList() {//打开借支公司列表
        this.showCompany = true;
      },
      closeCompanyList() {
        this.showCompany = false;
      },
      closeModal() {
        this.sendVal = false;
      },
      confirm() {//绑定工资卡
        this.sendVal = false;
        this.$router.push("/paycardManage");
      },
      inputBlur() {//input关闭键盘后导致页面底部空缺
        window.scrollTo(0, 0);
      },
      uploadPhoto(e) {//上传照片七牛云
        if (e.target.files.length > 0) {
          util.getBase64(e.target, (url) => {
            this.camera = 'data:image/png;base64,' + url;//base64图片
            //获取uploadToken
            this.axios.get(baseUrl + "/platform/get_token?sgin=" + this.userSign).then((res) => {
              let resultObj = res.data;
              var file = util.convertBase64ToBlob(this.camera) //Blob 对象，上传的文件
              var key = null // 上传后文件资源名以设置的 key 为主，如果 key 为 null 或者 undefined，则文件资源名会以 hash 值作为资源名。
              var config = {
                useCdnDomain: true, //表示是否使用 cdn 加速域名，为布尔值，true 表示使用，默认为 false。
                region: qiniu.region.z2 // 根据具体提示修改上传地区,当为 null 或 undefined 时，自动分析上传域名区域};
              }

              var putExtra = {
                fname: "", //文件原文件名
                params: {}, //用来放置自定义变量
                mimeType: null //用来限制上传文件类型，为 null 时表示不对文件类型限制；限制类型放到数组里： ["image/png", "image/jpeg", "image/gif"]
              };
              var observable = qiniu.upload(file, key, resultObj.data, putExtra, config);

              observable.subscribe({
                next: (res) => {//主要用来展示进度
                  let total = res.total;
                },
                error: (err) => {//失败报错信息
                  this.$vux.toast.text("图片上传失败，请重试", "middle");
                },
                complete: (res) => {//接收成功后返回的信息
                  this.upload = true;
                  this.photo = "http://pic.lanpin123.com/" + res.hash;
                }
              })
            })
          });
        }
      },
      lend() {//借支
        if (this.checkCompany() && this.checkPhone() && this.checkMoney()) {
          //查询借支记录
          this.axios.get(baseUrl + "/lendmoney/query_checkrecord?sgin=" + this.userSign).then((res) => {
            let resultObj = res.data;
            if (resultObj.code == 0) {
              if (resultObj.data) {
                if (resultObj.data.status == "0") {
                  this.$vux.toast.text("您已有一笔待审核的借支", "middle");
                  return;
                } else {
                  this.addLendMoney();
                }
              } else {
                this.addLendMoney();
              }
            } else {
              this.$vux.toast.text(resultObj.msg, "middle");
            }
          })
        }
      },
      addLendMoney() {//借支接口
        this.$vux.loading.show({
          text: '加载中',
        });

        this.axios.post(baseUrl + "/lendmoney/add_lendmoney_api?sgin=" + this.userSign + "&lendMoney=" + this.lendMoney + "&mechanismId=" + this.mechanismId + "&teacherTel=" + this.phone + "&userWorkImage=" + this.photo).then((res) => {
          let resultObj = res.data;
          this.$vux.loading.hide();
          if (resultObj.code == 0 && resultObj.data == 1) {
            this.$router.push("/lendDetail");
          } else {
            this.$vux.toast.text(resultObj.msg, "middle");
          }
        }).catch((error) => {
          this.$vux.loading.hide();
          this.$vux.toast.text("网络异常", "middle");
        });
      }
    },
    components: {
      "v-phone": phone,
      "v-warn": warn,
      "v-dialog": dialog
    }
  }
</script>

<style lang="stylus" scoped>
  @import "../../assets/stylus/mixin.styl"

  .lendWrap
    wh(100%, 100%)
    ::-webkit-input-placeholder
      /* Chrome/Opera/Safari */
      color: #FFF
    ::-moz-placeholder
      /* Firefox 19+ */
      color: #FFF
    :-ms-input-placeholder
      /* IE 10+ */
      color: #FFF;
    :-moz-placeholder
      /* Firefox 18- */
      color: #FFF
    .lend-bg
      wh(100%, 21.19%)
      bg-image("./bg1.png", 100%, 100%)
    .lend-box
      wh(100%, 78.81%)
      background: linear-gradient(0deg, rgba(60, 175, 255, 1), rgba(90, 187, 255, 1))
      overflow: hidden
      .lend-limit
        display: flex
        align-items: center
        margin: 0 auto
        width: 92.53%
        size-color(0.44rem, #FFF)
        font-weight: 500
        .limit-word
          margin-right: 0.05rem
        .limit_num
          font-size: 0.75rem
          padding-top: 0.375rem
      .num
        margin: 0.4rem auto
      .lend-company
        display: flex
        align-items: center
        margin: 0 auto
        margin-top: 0.2rem
        wh(92.53%, 1.107rem)
        size-color(0.44rem, #FFF)
        font-weight: 500
        position: relative
        .name
          margin-right: 0.05rem
        .company
          flex: 1
          height: 1.107rem
          background: none
          outline: none
          border: 1px solid rgba(255, 255, 255, 1)
          border-radius: 0.173333rem
          line-height: 1.107rem
          padding-left: 0.267rem
          ellipsis()
        .pull
          position: absolute;
          right: 0.213333rem;
          top: 0.466666rem;
          width: 0.387rem
          height: 0.2rem
      .lend-con
        display: flex
        align-items: center
        margin: 0 auto
        margin-top: 0.3rem
        wh(92.53%, 1.107rem)
        size-color(0.44rem, #FFF)
        font-weight: 500
        .title
          margin-right: 0.05rem
        .phone-box
          flex: 1
          height: 1.107rem
          border: 1px solid rgba(255, 255, 255, 1)
          border-radius: 0.173333rem
          line-height: 1.107rem
          .phone
            background: none
            outline: none
            margin-left: 0.267rem
            color: #FFF
      .lend-photo
        display: flex
        width: 92.53%
        margin: 0 auto
        margin-top: 0.4rem
        margin-bottom: 0.3rem
        height: 3.12rem
        position: relative
        .name
          color: #FFF
          margin-top: 0.64rem
          font-size: 0.44rem
        .photo-box
          width: 7.00rem
          height: 3.12rem
          border: 1px solid rgba(216, 216, 216, 1)
          border-radius: 0.106666rem
          .camera-box
            position: relative
            margin: 0 auto
            width: 2.293333rem
            height: 1.626666rem
            border: 1px solid rgba(216, 216, 216, 1)
            border-radius: 0.106666rem
            margin-top: 0.24rem
            .photo
              position: absolute
              left: 0
              top: 0
              width: 100%
              height: 100%
              border-radius: 0.226666rem
              opacity: 0
              -ms-filter: 'alpha(opacity=0)'
              z-index: 88
            .camera
              display: flex
              justify-content: center
              margin: 0 auto
              width: 0.746666rem
              height: 0.626666rem
              margin-top: 0.253333rem
            .upload
              margin-top: 0.2rem
              color: #FFF
              font-size: 0.333333rem
              font-weight: 500
              display: flex
              justify-content: center
          .tips
            margin: 0 auto
            width: 90%
            margin-top: 0.24rem
            font-size: 0.346666rem
            font-weight: 500
            color: rgba(255, 255, 255, 1)
            line-height: 0.44rem
        .uploadImg
          position: absolute
          width: 7.00rem
          height: 3.12rem
          right: 0.05rem
          border-radius: 0.106666rem
      .lend-word
        width: 92.53%
        font-size: 0.36rem
        line-height: 0.44rem
        color: #FFF
        margin: 0 auto
        margin-bottom: 0.4rem
      .lend-btn
        wh(100%, 1.333333rem)
        text-align: center
        .sure
          wh(92.53%, 1.333333rem)
          border: 1px solid rgba(51, 167, 241, 1)
          border-radius(0.173333rem)
          size-color(0.48rem, #3CAFFF)
          background: #FFF
      .company-box
        position: fixed
        top: 0
        left: 0
        right: 0
        bottom: 0
        z-index: 88
        fj(center, center)
        background-color: rgba(0, 0, 0, 0.5)
        .company-list
          position: absolute
          z-index: 99
          bottom: 0
          left: 0
          wh(100%, 6.44rem)
          background: #FFF
          overflow: auto;
          .name
            fj(center, center)
            height: 1.28rem
            border-bottom: 0.013333rem solid #EEE
            cursor: pointer
            size-color(0.44rem, #666666)
            &:hover
              color: #3CAFFF
</style>
